import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/models/loc_obj.dart';
import 'package:xws/utils/loc_util.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';

/// 添加地址
class AddAddr extends StatefulWidget {
  const AddAddr({
    Key? key,
    this.initValue,
    this.onCoordinateChanged,
  }) : super(key: key);

  @override
  _AddAddrState createState() => _AddAddrState();

  final String? initValue;
  final Function(LocObj? loc)? onCoordinateChanged;
}

class _AddAddrState extends State<AddAddr> with SafeState<AddAddr> {
  String _text = '定位中...';
  late Color _color = disable(context);

  @override
  Future<void> contextReady() {
    _init();
    return super.contextReady();
  }

  Future<void> _init() async {
    if (widget.initValue != null) {
      _text = widget.initValue!;
      _color = theme(context);
      safeSetState(() {});
    } else {
      await _refresh();
    }
  }

  /// 刷新
  Future<void> _refresh({bool isRefresh = false}) async {
    if (isRefresh) {
      safeSetState(() {
        _text = '定位中...';
        _color = disable(context);
      });
    }

    final LocObj? loc = await getLocation();

    if (!mounted) return;

    if (loc == null) {
      _text = '定位失败';
      widget.onCoordinateChanged?.call(null);
    } else {
      _text = (loc.city ?? '') + ' ' + (loc.district ?? '');
      _color = theme(context);
      widget.onCoordinateChanged?.call(loc);
    }

    safeSetState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return AppBtn(
      onTap: () => _refresh(isRefresh: true),
      height: 40,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Icon(
            Icons.location_on_rounded,
            size: 18,
            color: _color,
          ),
          const SizedBox(width: 4),
          Text(
            _text,
            style: TextStyle(fontSize: 13, color: _color),
          ),
        ],
      ),
      color: canvas(context),
      radius: 4,
      padding: const EdgeInsets.symmetric(horizontal: 10),
    );
  }
}
